from flask import Flask, request, jsonify, send_file, Response
from flask_cors import CORS
import requests
import os
import tempfile
import uuid
from urllib.parse import urlparse
import mimetypes
import time
import random
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置临时文件目录
TEMP_DIR = tempfile.gettempdir()

# 创建会话对象，配置重试策略
def create_session():
    session = requests.Session()
    retry_strategy = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

@app.route('/download-image', methods=['POST'])
def download_image():
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        # 解析URL获取域名
        parsed_url = urlparse(image_url)
        domain = f"{parsed_url.scheme}://{parsed_url.netloc}"
        
        # 随机延迟，避免频率限制
        time.sleep(random.uniform(0.5, 2.0))
        
        # 创建会话
        session = create_session()
        
        # 更强大的用户代理和请求头策略
        user_agents = [
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        ]
        
        # 基础请求头
        base_headers = {
            'User-Agent': random.choice(user_agents),
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'DNT': '1'
        }
        
        # 多次尝试不同的策略
        strategies = [
            # 策略1：基础请求头
            {'headers': base_headers.copy()},
            
            # 策略2：添加Coze相关的referer
            {'headers': {**base_headers, 'Referer': 'https://www.coze.cn/', 'Origin': 'https://www.coze.cn'}},
            
            # 策略3：使用图片域名作为referer
            {'headers': {**base_headers, 'Referer': domain, 'Origin': domain}},
            
            # 策略4：模拟从搜索引擎访问
            {'headers': {**base_headers, 'Referer': 'https://www.google.com/', 'Origin': 'https://www.google.com'}},
            
            # 策略5：添加更多浏览器特征
            {'headers': {**base_headers, 
                        'Sec-Fetch-Dest': 'image',
                        'Sec-Fetch-Mode': 'no-cors',
                        'Sec-Fetch-Site': 'cross-site',
                        'Sec-Ch-Ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
                        'Sec-Ch-Ua-Mobile': '?0',
                        'Sec-Ch-Ua-Platform': '"Windows"'}},
            
            # 策略6：完全模拟浏览器直接访问
            {'headers': {**base_headers, 
                        'Referer': image_url,
                        'X-Requested-With': 'XMLHttpRequest'}},
            
            # 策略7：移除所有可能触发反爬的头部
            {'headers': {'User-Agent': random.choice(user_agents), 'Accept': '*/*'}}
        ]
        
        last_error = None
        
        for i, strategy in enumerate(strategies):
            try:
                print(f"尝试策略 {i+1}: {strategy}")
                
                # 发送请求下载图片
                response = session.get(
                    image_url, 
                    headers=strategy['headers'], 
                    timeout=30, 
                    stream=True,
                    allow_redirects=True
                )
                
                print(f"响应状态码: {response.status_code}")
                print(f"响应头: {dict(response.headers)}")
                
                if response.status_code == 200:
                    break
                elif response.status_code == 403:
                    print(f"策略 {i+1} 被拒绝 (403)，尝试下一个策略")
                    continue
                else:
                    last_error = f"HTTP {response.status_code}"
                    continue
                    
            except Exception as e:
                print(f"策略 {i+1} 失败: {str(e)}")
                last_error = str(e)
                continue
        else:
            # 所有策略都失败了
            return jsonify({
                'error': f'所有下载策略都失败了。最后错误: {last_error}',
                'status_code': getattr(response, 'status_code', 0) if 'response' in locals() else 0
            }), 400
        
        if response.status_code == 200:
            # 获取文件扩展名
            content_type = response.headers.get('content-type', '')
            if 'image/jpeg' in content_type or 'image/jpg' in content_type:
                ext = '.jpg'
            elif 'image/png' in content_type:
                ext = '.png'
            elif 'image/gif' in content_type:
                ext = '.gif'
            elif 'image/webp' in content_type:
                ext = '.webp'
            else:
                ext = '.jpg'  # 默认扩展名
            
            # 生成临时文件名
            filename = f"image_{uuid.uuid4().hex}{ext}"
            filepath = os.path.join(TEMP_DIR, filename)
            
            # 保存图片到临时文件
            with open(filepath, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            
            return jsonify({
                'success': True,
                'message': '图片下载成功',
                'download_url': f'/get-image/{filename}',
                'original_url': image_url,
                'content_type': content_type,
                'file_size': os.path.getsize(filepath)
            })
        else:
            return jsonify({
                'error': f'下载失败，状态码: {response.status_code}',
                'status_code': response.status_code
            }), 400
            
    except requests.exceptions.Timeout:
        return jsonify({'error': '请求超时，请稍后重试'}), 408
    except requests.exceptions.ConnectionError:
        return jsonify({'error': '网络连接错误'}), 503
    except Exception as e:
        return jsonify({'error': f'下载失败: {str(e)}'}), 500

@app.route('/get-image/<filename>', methods=['GET'])
def get_image(filename):
    try:
        filepath = os.path.join(TEMP_DIR, filename)
        
        if not os.path.exists(filepath):
            return jsonify({'error': '文件不存在'}), 404
        
        # 获取MIME类型
        mimetype = mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
        
        return send_file(filepath, mimetype=mimetype, as_attachment=True, download_name=filename)
        
    except Exception as e:
        return jsonify({'error': f'获取文件失败: {str(e)}'}), 500

@app.route('/proxy-image', methods=['POST'])
def proxy_image():
    """直接代理图片，不保存到本地"""
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        # 随机延迟，避免频率限制
        time.sleep(random.uniform(0.3, 1.5))
        
        # 创建会话
        session = create_session()
        
        # 解析URL获取域名
        parsed_url = urlparse(image_url)
        domain = f"{parsed_url.scheme}://{parsed_url.netloc}"
        
        # 使用与下载相同的策略
        user_agents = [
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0'
        ]
        
        headers = {
            'User-Agent': random.choice(user_agents),
            'Referer': 'https://www.coze.cn/',
            'Origin': 'https://www.coze.cn',
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Sec-Fetch-Dest': 'image',
            'Sec-Fetch-Mode': 'no-cors',
            'Sec-Fetch-Site': 'cross-site',
            'Cache-Control': 'no-cache'
        }
        
        # 多策略尝试
        strategies = [
            {'headers': headers},
            {'headers': {**headers, 'Referer': domain, 'Origin': domain}},
            {'headers': {**headers, 'Referer': image_url}}
        ]
        
        for i, strategy in enumerate(strategies):
            try:
                response = session.get(
                    image_url, 
                    headers=strategy['headers'],
                    timeout=30,
                    allow_redirects=True
                )
                
                if response.status_code == 200:
                    # 直接返回图片数据
                    content_type = response.headers.get('content-type', 'image/jpeg')
                    return Response(
                        response.content,
                        mimetype=content_type,
                        headers={
                            'Content-Type': content_type,
                            'Cache-Control': 'public, max-age=3600',
                            'Access-Control-Allow-Origin': '*'
                        }
                    )
                elif response.status_code == 403:
                    continue
                else:
                    continue
                    
            except Exception as e:
                print(f"代理策略 {i+1} 失败: {str(e)}")
                continue
        
        # 所有策略都失败
        return jsonify({
            'error': '所有代理策略都失败了，可能是访问限制'
        }), 403
            
    except Exception as e:
        return jsonify({'error': f'代理失败: {str(e)}'}), 500

@app.route('/coze-image', methods=['POST'])
def coze_image_proxy():
    """专门处理Coze图片的代理，使用更激进的反403策略"""
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        # 创建会话，禁用SSL验证以绕过某些限制
        session = requests.Session()
        session.verify = False
        
        # 针对Tengine服务器的特殊策略
        tengine_strategies = [
            # 策略1：完全模拟真实浏览器访问
            {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
                'Referer': 'https://www.coze.cn/',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'Accept-Encoding': 'gzip, deflate, br',
                'Connection': 'keep-alive',
                'Upgrade-Insecure-Requests': '1',
                'Sec-Fetch-Dest': 'document',
                'Sec-Fetch-Mode': 'navigate',
                'Sec-Fetch-Site': 'none',
                'Sec-Fetch-User': '?1',
                'Cache-Control': 'max-age=0'
            },
            
            # 策略2：模拟微信内置浏览器
            {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/88.0.4324.181 Mobile Safari/537.36 MicroMessenger/8.0.1',
                'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'X-Requested-With': 'com.tencent.mm'
            },
            
            # 策略3：模拟搜索引擎爬虫
            {
                'User-Agent': 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)',
                'Accept': '*/*'
            },
            
            # 策略4：模拟CDN回源请求
            {
                'User-Agent': 'Mozilla/5.0 (compatible; CloudFlare-AlwaysOnline/1.0; +http://www.cloudflare.com/always-online)',
                'CF-RAY': f'{random.randint(100000000000000000, 999999999999999999)}-HKG',
                'CF-Visitor': '{"scheme":"https"}',
                'Accept': 'image/*,*/*;q=0.8'
            },
            
            # 策略5：模拟内网访问
            {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'X-Forwarded-For': '127.0.0.1',
                'X-Real-IP': '127.0.0.1',
                'X-Forwarded-Proto': 'https',
                'Accept': 'image/*'
            },
            
            # 策略6：模拟API客户端
            {
                'User-Agent': 'okhttp/4.9.0',
                'Accept': 'application/octet-stream',
                'Connection': 'close'
            },
            
            # 策略7：最简策略
            {
                'User-Agent': 'wget/1.20.3',
                'Accept': '*/*'
            },
            
            # 策略8：模拟图片处理服务
            {
                'User-Agent': 'ImageMagick/7.0.10-6',
                'Accept': 'image/*'
            }
        ]
        
        for i, headers in enumerate(tengine_strategies):
            try:
                print(f"尝试反Tengine策略 {i+1}")
                
                # 随机延迟，模拟人类行为
                time.sleep(random.uniform(0.5, 2.5))
                
                # 添加随机的会话标识
                if 'Cookie' not in headers:
                    headers['Cookie'] = f'session_id={uuid.uuid4().hex[:16]}; _ga=GA1.2.{random.randint(1000000000, 9999999999)}.{int(time.time())}'
                
                response = session.get(
                    image_url,
                    headers=headers,
                    timeout=30,
                    allow_redirects=True,
                    stream=True
                )
                
                print(f"反Tengine策略 {i+1} 响应: {response.status_code}")
                print(f"响应头: {dict(list(response.headers.items())[:5])}")  # 只打印前5个响应头
                
                if response.status_code == 200:
                    # 成功获取图片
                    content_type = response.headers.get('content-type', 'image/jpeg')
                    
                    # 读取图片内容
                    image_content = b''
                    for chunk in response.iter_content(chunk_size=8192):
                        image_content += chunk
                    
                    print(f"成功获取图片，大小: {len(image_content)} 字节")
                    
                    return Response(
                        image_content,
                        mimetype=content_type,
                        headers={
                            'Content-Type': content_type,
                            'Content-Length': str(len(image_content)),
                            'Cache-Control': 'public, max-age=3600',
                            'Access-Control-Allow-Origin': '*',
                            'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
                            'Access-Control-Allow-Headers': 'Content-Type'
                        }
                    )
                elif response.status_code == 403:
                    print(f"反Tengine策略 {i+1} 被拒绝 (403)，尝试下一个")
                    continue
                elif response.status_code == 404:
                    print(f"图片不存在 (404)")
                    return jsonify({'error': '图片不存在或已被删除'}), 404
                else:
                    print(f"反Tengine策略 {i+1} 返回状态码: {response.status_code}")
                    continue
                    
            except requests.exceptions.Timeout:
                print(f"反Tengine策略 {i+1} 超时")
                continue
            except requests.exceptions.ConnectionError as e:
                print(f"反Tengine策略 {i+1} 连接错误: {str(e)}")
                continue
            except Exception as e:
                print(f"反Tengine策略 {i+1} 异常: {str(e)}")
                continue
        
        return jsonify({
            'error': '所有反Tengine策略都失败了',
            'message': '目标服务器可能有更严格的访问限制',
            'suggestion': '请尝试复制链接到浏览器中直接访问'
        }), 403
        
    except Exception as e:
        return jsonify({'error': f'反Tengine代理失败: {str(e)}'}), 500

@app.route('/tengine-bypass', methods=['POST'])
def tengine_bypass():
    """专门绕过Tengine服务器限制的终极策略"""
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        print(f"尝试绕过Tengine限制: {image_url}")
        
        # 创建特殊会话
        session = requests.Session()
        session.verify = False  # 禁用SSL验证
        
        # 设置代理（如果需要）
        # session.proxies = {'http': 'http://proxy:port', 'https': 'https://proxy:port'}
        
        # 终极绕过策略
        ultimate_strategies = [
            # 策略1：模拟curl命令行工具
            {
                'User-Agent': 'curl/7.68.0',
                'Accept': '*/*',
                'Connection': 'close'
            },
            
            # 策略2：模拟wget
            {
                'User-Agent': 'Wget/1.20.3 (linux-gnu)',
                'Accept': '*/*',
                'Connection': 'Keep-Alive'
            },
            
            # 策略3：模拟Python requests
            {
                'User-Agent': 'python-requests/2.28.1',
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate',
                'Connection': 'keep-alive'
            },
            
            # 策略4：模拟Postman
            {
                'User-Agent': 'PostmanRuntime/7.29.2',
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate, br',
                'Connection': 'keep-alive'
            },
            
            # 策略5：模拟内部服务调用
            {
                'User-Agent': 'internal-service/1.0',
                'X-Internal-Request': 'true',
                'X-Service-Name': 'image-processor',
                'Accept': 'image/*'
            },
            
            # 策略6：完全空的User-Agent
            {
                'Accept': '*/*'
            },
            
            # 策略7：模拟老版本浏览器
            {
                'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
                'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*'
            },
            
            # 策略8：模拟RSS阅读器
            {
                'User-Agent': 'FeedReader/1.0',
                'Accept': '*/*'
            }
        ]
        
        for i, headers in enumerate(ultimate_strategies):
            try:
                print(f"尝试终极策略 {i+1}")
                
                # 更长的随机延迟
                time.sleep(random.uniform(1.0, 3.0))
                
                # 尝试不同的请求方法
                methods = ['GET']
                if i % 2 == 0:  # 偶数策略尝试HEAD请求
                    methods.insert(0, 'HEAD')
                
                for method in methods:
                    try:
                        if method == 'HEAD':
                            response = session.head(
                                image_url,
                                headers=headers,
                                timeout=20,
                                allow_redirects=True
                            )
                            if response.status_code == 200:
                                # HEAD成功，再用GET获取内容
                                response = session.get(
                                    image_url,
                                    headers=headers,
                                    timeout=30,
                                    allow_redirects=True,
                                    stream=True
                                )
                        else:
                            response = session.get(
                                image_url,
                                headers=headers,
                                timeout=30,
                                allow_redirects=True,
                                stream=True
                            )
                        
                        print(f"终极策略 {i+1} ({method}) 响应: {response.status_code}")
                        
                        if response.status_code == 200:
                            # 成功获取图片
                            content_type = response.headers.get('content-type', 'image/jpeg')
                            
                            # 读取图片内容
                            image_content = b''
                            for chunk in response.iter_content(chunk_size=8192):
                                image_content += chunk
                            
                            if len(image_content) > 0:
                                print(f"终极策略成功！图片大小: {len(image_content)} 字节")
                                
                                return Response(
                                    image_content,
                                    mimetype=content_type,
                                    headers={
                                        'Content-Type': content_type,
                                        'Content-Length': str(len(image_content)),
                                        'Cache-Control': 'public, max-age=3600',
                                        'Access-Control-Allow-Origin': '*',
                                        'X-Bypass-Method': f'ultimate-{i+1}-{method}'
                                    }
                                )
                            else:
                                print(f"终极策略 {i+1} 返回空内容")
                                continue
                        
                        elif response.status_code == 403:
                            print(f"终极策略 {i+1} ({method}) 仍被拒绝")
                            continue
                        else:
                            print(f"终极策略 {i+1} ({method}) 状态码: {response.status_code}")
                            continue
                            
                    except Exception as method_error:
                        print(f"终极策略 {i+1} ({method}) 异常: {str(method_error)}")
                        continue
                        
            except Exception as e:
                print(f"终极策略 {i+1} 失败: {str(e)}")
                continue
        
        # 如果所有策略都失败，返回详细错误信息
        return jsonify({
            'error': '所有终极绕过策略都失败了',
            'message': 'Tengine服务器的访问限制非常严格',
            'suggestions': [
                '1. 尝试复制链接到浏览器中直接访问',
                '2. 检查图片链接是否有效',
                '3. 图片可能需要登录或特殊权限才能访问',
                '4. 服务器可能有IP限制或地理位置限制'
            ],
            'url': image_url
        }), 403
        
    except Exception as e:
        return jsonify({'error': f'终极绕过策略失败: {str(e)}'}), 500

@app.route('/multi-proxy', methods=['POST'])
def multi_proxy():
    """使用多个图片代理服务绕过防盗链"""
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        print(f"尝试多代理服务获取图片: {image_url}")
        
        # 清理URL
        clean_url = image_url.replace('https://', '').replace('http://', '')
        
        # 多个图片代理服务
        proxy_services = [
            {
                'name': 'weserv.nl',
                'url': f"https://images.weserv.nl/?url={clean_url}",
                'headers': {}
            },
            {
                'name': 'imageproxy.pimg.tw',
                'url': f"https://imageproxy.pimg.tw/resize?url={image_url}",
                'headers': {}
            },
            {
                'name': 'pic1.xuehuaimg.com',
                'url': f"https://pic1.xuehuaimg.com/proxy/{image_url}",
                'headers': {}
            },
            {
                'name': 'search.pstatic.net',
                'url': f"https://search.pstatic.net/common/?src={image_url}",
                'headers': {}
            },
            {
                'name': 'i0.wp.com',
                'url': f"https://i0.wp.com/{clean_url}",
                'headers': {}
            }
        ]
        
        # 创建会话
        session = create_session()
        
        for i, proxy in enumerate(proxy_services):
            try:
                print(f"尝试代理服务 {i+1}: {proxy['name']}")
                
                response = session.get(
                    proxy['url'],
                    headers=proxy['headers'],
                    timeout=20,
                    allow_redirects=True,
                    stream=True
                )
                
                print(f"{proxy['name']} 响应: {response.status_code}")
                
                if response.status_code == 200:
                    # 检查响应是否为图片
                    content_type = response.headers.get('content-type', '')
                    if 'image' in content_type or 'octet-stream' in content_type:
                        # 读取图片内容
                        image_content = b''
                        for chunk in response.iter_content(chunk_size=8192):
                            image_content += chunk
                        
                        # 验证图片内容
                        if len(image_content) > 1000:  # 至少1KB，避免错误页面
                            print(f"{proxy['name']} 代理成功！图片大小: {len(image_content)} 字节")
                            
                            return Response(
                                image_content,
                                mimetype=content_type if 'image' in content_type else 'image/jpeg',
                                headers={
                                    'Content-Type': content_type if 'image' in content_type else 'image/jpeg',
                                    'Content-Length': str(len(image_content)),
                                    'Cache-Control': 'public, max-age=3600',
                                    'Access-Control-Allow-Origin': '*',
                                    'X-Proxy-Service': proxy['name']
                                }
                            )
                        else:
                            print(f"{proxy['name']} 返回内容太小，可能是错误页面")
                            continue
                    else:
                        print(f"{proxy['name']} 返回非图片内容: {content_type}")
                        continue
                else:
                    print(f"{proxy['name']} 返回状态码: {response.status_code}")
                    continue
                    
            except Exception as e:
                print(f"{proxy['name']} 异常: {str(e)}")
                continue
        
        # 所有代理服务都失败
        return jsonify({
            'error': '所有图片代理服务都失败了',
            'tried_services': [p['name'] for p in proxy_services],
            'original_url': image_url
        }), 403
        
    except Exception as e:
        return jsonify({'error': f'多代理服务失败: {str(e)}'}), 500

@app.route('/weserv-proxy', methods=['POST'])
def weserv_proxy():
    """使用weserv.nl服务绕过防盗链"""
    try:
        data = request.get_json()
        image_url = data.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少图片URL参数'}), 400
        
        # 移除URL中的协议前缀，weserv.nl会自动处理
        clean_url = image_url.replace('https://', '').replace('http://', '')
        
        # 构建weserv代理URL，添加更多参数来提高成功率
        weserv_url = f"https://images.weserv.nl/?url={clean_url}&w=800&h=600&fit=inside&we"
        
        print(f"使用weserv代理: {weserv_url}")
        
        # 创建会话
        session = create_session()
        
        try:
            response = session.get(
                weserv_url,
                timeout=30,
                allow_redirects=True,
                stream=True,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
                    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
                    'Referer': 'https://images.weserv.nl/'
                }
            )
            
            print(f"weserv代理响应: {response.status_code}")
            
            if response.status_code == 200:
                # 成功获取图片
                content_type = response.headers.get('content-type', 'image/jpeg')
                
                # 读取图片内容
                image_content = b''
                for chunk in response.iter_content(chunk_size=8192):
                    image_content += chunk
                
                print(f"weserv代理成功！图片大小: {len(image_content)} 字节")
                
                return Response(
                    image_content,
                    mimetype=content_type,
                    headers={
                        'Content-Type': content_type,
                        'Content-Length': str(len(image_content)),
                        'Cache-Control': 'public, max-age=3600',
                        'Access-Control-Allow-Origin': '*',
                        'X-Proxy-Service': 'weserv.nl'
                    }
                )
            else:
                return jsonify({
                    'error': f'weserv代理失败，状态码: {response.status_code}',
                    'weserv_url': weserv_url
                }), response.status_code
                
        except Exception as e:
            return jsonify({
                'error': f'weserv代理异常: {str(e)}',
                'weserv_url': weserv_url
            }), 500
        
    except Exception as e:
        return jsonify({'error': f'weserv代理服务失败: {str(e)}'}), 500

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'ok', 'message': '图片代理服务运行正常'})

if __name__ == '__main__':
    print("图片代理服务启动中...")
    print("API端点:")
    print("  POST /download-image - 下载图片到服务器")
    print("  GET /get-image/<filename> - 获取已下载的图片")
    print("  POST /proxy-image - 直接代理图片")
    print("  GET /health - 健康检查")
    app.run(host='0.0.0.0', port=5000, debug=True)